﻿// home-index.js

var homeIndexModule = angular.module("homeIndex", ['ngRoute']);

homeIndexModule.config(["$routeProvider",
    function ($routeProvider) {
        //define individual route
        $routeProvider.when("/", {
            controller: "topicsController",
            templateUrl: "/templates/topicsView.html",
        });

        $routeProvider.when("/newmessage", {
            controller: "newTopicController",
            templateUrl: "/templates/newTopicView.html",
        });

        $routeProvider.when("/message/:id", {
            controller: "singleTopicController",
            templateUrl: "/templates/singleTopicView.html"
        });

        $routeProvider.otherwise({ redirectTo: '/' });
    }]);

homeIndexModule.factory("dataService", ["$http", "$q",
    function ($http, $q) {
        var _topics = [];
        var _isInit = false;

        var _isReady = function () {
            return _isInit;
        };

        //fill the topics in the data service
        var _getTopics = function () {

            var deffered = $q.defer();

            $http.get("/api/topics/includeReplies=true")
                .then(function (result) {
                    //successful
                    angular.copy(result.data, _topics);
                    //initialized 
                    _isInit = true;
                    deffered.resolve(); //resolve with successful result
                },
                    function () {
                        //error 
                        deffered.reject();//unseccessful result
                    });

            return deffered.promise;
        };

        var _addTopic = function (newTopic) {
            var defferred = $q.defer();

            $http.post("api/Topics", newTopic)
                .then(function (result) {
                    //success
                    var newlyCreatedTopic = result.data;
                    //Tmerge with existing list of topics
                    _topics.splice(0, 0, newlyCreatedTopic);
                    defferred.resolve(newlyCreatedTopic);
                },
                    function () {
                        //error
                        defferred.reject();
                    });


            return defferred.promise;
        };

        function _findTopic(id) {
            var found = null;


            $.each(_topics, function (i, item) {
                if (item.id == id) {
                    found = item;
                    return false;
                }
            });

            return found;
        }

        var _getTopicById = function (id) {
            var deffered = $q.defer();

            if (_isReady()) {
                var topic = _findTopic(id);
                if (topic) {
                    deffered.resolve(topic);
                } else {
                    deffered.reject();
                }
            } else {
                _getTopics()
                    .then(function () {
                        //success
                        var topic = _findTopic(id);
                        if (topic) {
                            deffered.resolve(topic);
                        } else {
                            deffered.reject();
                        }
                    },
                    function () {
                        //error
                        deffered.reject();
                    });
            }
            return deffered.promise;
        };

        var _saveReply = function (topic, newReply) {
            var deferred = $q.defer();

            $http.post("/api/topics/" + topic.id + "/replies", newReply)
                .then(function (result) {
                    //success
                    if (topic.replies == null)
                        topic.replies = [];

                    topic.replies.push(result.data);
                    deferred.resolve(result.data);
                },
                function () {
                    //error
                    deferred.reject();
                });
            return deferred.promise;
        };


        return {
            topics: _topics,
            getTopics: _getTopics,
            addTopic: _addTopic,
            isReady: _isReady,
            getTopicById: _getTopicById,
            saveReply: _saveReply,
        };
    }]);

var topicsController = ["$scope", "$http", "dataService",
    function ($scope, $http, dataService) {
    $scope.data = dataService.topics;
    $scope.isBusy = false;
    if (dataService.isReady() == false) {
        $scope.isBusy = false;
        dataService.getTopics()
            .then(function () {
                //success
            },
                function () {
                    //error
                    alert("Could not load topics");
                })
            .then(function () {
                $scope.isBusy = false;
            });
    }

}];

var newTopicController = ["$scope", "$http", "$window", "dataService",
    function($scope, $http,$window, dataService) {
        $scope.newTopic = { };
        $scope.save = function() {
            dataService.addTopic($scope.newTopic)
                .then(function() {
                    //success

                    $window.location = "#/";
                }, function() {
                    //errror
                    alert("Could not save the new topic");
                });
        };
    }];

var singleTopicController = ["$scope", "dataService", "$window", "$routeParams",
    function($scope, dataService, $window, $routeParams) {
        $scope.topic = null;
        $scope.newReply = { };

        dataService.getTopicById($routeParams.id)
            .then(function(topic) {
                //success
                $scope.topic = topic;
            },
                function() {
                    //errror
                    $window.location = "#/";
                });

        $scope.addReply = function() {
            dataService.saveReply($scope.topic, $scope.newReply)
                .then(function() {
                    //success
                    $scope.newReply.body = "";
                },
                    function() {
                        //error
                        alert("Could not save the new reply");
                    });
        };
    }];

